package com.jldx.oa.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

import com.google.zxing.WriterException;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jldx.common.QRCodeUtil;
import com.jldx.common.Result;
import com.jldx.oa.bean.Goods;
import com.jldx.oa.bean.GoodsCategory;

public class GoodsController extends BaseController {

	public void index() {
		render("/WEB-INF/views/goods.html");
	}

	public void query() {
		Integer pageNumber = getPage();
		String name = getPara("name");
		Integer limit = getLimit();
		Kv cond = Kv.by("name", name);
		SqlPara sqlPara = Db.getSqlPara("oa.goodsList", cond);
		Page<Goods> page = Goods.dao.paginate(pageNumber, limit, sqlPara);
		Result result = Result.cast(page);
		renderJson(result);
	}

	public void edit() {
		Integer id = getParaToInt("id");
		if (id != null) {
			Goods goods = Goods.dao.findById(id);
			setAttr("goods", goods);
		}
		List<GoodsCategory> gcs = GoodsCategory.dao.find("select * from goods_category");
		setAttr("gcs", gcs);
		view("goods_edit.html");
	}

	public void detail() {
		Integer id = getParaToInt("id");
		Goods goods = Goods.dao.findById(id);
		renderJson(goods);
	}

	public void save() {
		Goods goods = getModel(Goods.class, "");
		if (goods.getId() != null) {
			goods.update();
		} else {
			goods.save();
		}
		renderText("suc");
	}

	public void delete() {
		Integer id = getParaToInt("id");
		boolean result = false;
		if (id != null) {
			result = Goods.dao.deleteById(id);
		}
		if (result) {
			renderText("suc");
		} else {
			render("fail");
		}
	}
	
	public void code(){
		Integer id = getParaToInt("id");
		setAttr("id", id);
		view("goods_code.html");
	}
	
	public void codeImg() throws WriterException, IOException{
		Integer id = getParaToInt();
		BufferedImage img = QRCodeUtil.createImage(id.toString(), "", true);
		ImageIO.write(img, "jpeg", getResponse().getOutputStream());
		renderNull();
	}
}
